# -*- coding: utf-8 -*-
# Copyright © 2015 Beijing HengXingChangDa Technology Co., Ltd. All rights reserved.


from django.db import models
from mjs.config import *
import django.utils.timezone as timezone
import requests
import json

from proto.csm import *


class CSMUser(models.Model):
    token = models.CharField(max_length=COWS_TOKEN_LEN, unique=True)
    csm_slice_id = models.CharField(max_length=COWS_USERID_LEN)
    csm_user_id = models.CharField(max_length=COWS_USERID_LEN)
    firstname = models.CharField(max_length=COWS_USERID_LEN)
    lastname = models.CharField(max_length=COWS_USERID_LEN)
    username = models.CharField(max_length=COWS_USERID_LEN, unique=True)
    password = models.CharField(max_length=COWS_USERID_LEN)
    # contact_id = models.CharField(max_length=COWS_USERID_LEN)
    email = models.CharField(max_length=COWS_USERID_LEN)
    cookies = models.CharField(max_length=COWS_USERID_LEN)
    mpid = models.CharField(max_length=COWS_COOKIE_LEN)
    btime = models.DateTimeField(auto_now_add=True)
    mtime = models.DateTimeField(auto_now=True)

    @staticmethod
    def get_all(get_related=False):
        all_objects = CSMUser.objects.all()
        return all_objects

    def to_dict(self, detail=True):
        d = dict()
        return d

    def setCookie(self, cookies):
        d = requests.utils.dict_from_cookiejar(cookies)
        s = json.dumps(d,
                       # indent=4,
                       ensure_ascii=False)
        self.cookies = s

    def getCookie(self):
        d = json.loads(self.cookies)
        return requests.utils.cookiejar_from_dict(d)

    def refreshCookie(self):
        csmres, cookies = csm_user_login(self.username, self.password)
        self.setCookie(cookies)
        self.save()
